//
//  VideoViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/17.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "VideoViewController.h"
#import <AFNetworking.h>
#import "AfNetWorkingHandler.h"
#import "KindModel.h"
#import "Videomodel.h"
#import "KindCell.h"
#import "VideoTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "KindViewController.h"
#import <MJRefresh.h>
#import <MediaPlayer/MediaPlayer.h>
#import <View+MASAdditions.h>
#import "MBProgressHUDManager.h"//加载时的小菊花
#import "UMSocial.h"//友盟分享
#import "SetBlack.h"
#import "BlackManager.h"
#import "DateBaseManager.h"
#import "VideoDetaileViewController.h"
#import "LoginViewController.h"
@interface VideoViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, shareDelegate>
@property (nonatomic, retain)NSMutableArray *ListArr;//下面列表的数据
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *kindArr;//上面分类的数据
@property (nonatomic, retain)UICollectionView *collection;
@property (nonatomic, assign)NSInteger number;//请求数据的个数
@property (nonatomic, retain)MPMoviePlayerViewController *movieView;
@property (nonatomic, retain)NSIndexPath *indexpath;//点击的cell的位置
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, assign)BOOL isfull;
@property (nonatomic, assign)CGRect selectedRect;
@property (nonatomic, retain)VideoTableViewCell *cell;
@property (nonatomic, assign)NSInteger i;
@end

@implementation VideoViewController
-(void)dealloc
{
    [_ListArr release];
    [_tableView release];
    [_kindArr release];
    [_collection release];
    [_movieView release];
    [_indexpath release];
    [_button release];
    [_cell release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{
    [_collection reloadData];
    [_tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"视频";
    //数据处理
    [self dataHandler];
    //tableView
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    [_tableView release];
    //tableView头部区域
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, (self.view.frame.size.height - 64) / 6 )];
//    view.backgroundColor = [UIColor yellowColor];
    _tableView.tableHeaderView = view;
    [view release];
    //头部的collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 3) / 4, (self.view.frame.size.height - 64) / 6 - 10);
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, (self.view.frame.size.height - 64) / 6) collectionViewLayout:layout];
    [_collection registerClass:[KindCell class] forCellWithReuseIdentifier:@"kindcell"];
    _collection.dataSource = self;
    _collection.delegate = self;
    _collection.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:_collection];
    [layout release];
    [_collection release];
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [_tableView.mj_header beginRefreshing];
    //上拉加载
    self.number = 10;
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadnewdata)];
    if (_ListArr.count != 0) {
        [_tableView.mj_footer beginRefreshing];
    }
    //隐藏上下边栏
    //是否实现了方法
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;//取消scrollview的内容自动调整
        UIEdgeInsets insets = self.tableView.contentInset ;//tableView边界预留
        insets.top = self.navigationController.navigationBar.bounds.size.height;//让上边界的预留值和导航栏相等
//        self.tableView.contentInset = insets;
        self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
        //把修改后的边界预留值赋值给tableView
        self.tableView.scrollIndicatorInsets = insets;//滚动指标点到滚动视图的边缘的距离
        
    }
    //视频监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpFullScreen) name:@"MPMoviePlayerWillEnterFullscreenNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen) name:@"MPMoviePlayerWillExitFullscreenNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removecell) name:@"remove" object:nil];
    

}

//通知中心 让视频停掉
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
}
-(void)removecell
{
    if (self.movieView.view) {
//        self.movieView.moviePlayer.pause;
        [self.movieView.view removeFromSuperview];
    }
}
- (void)jumpFullScreen {
    
    self.isfull = YES;
    
}

- (void)exitFullScreen {
    self.isfull = NO;
}
//将要离开页面时 移除
-(void)viewWillDisappear:(BOOL)animated
{
    if (!self.isfull) {
        if (self.movieView.view) {
            [self.movieView.view removeFromSuperview];
        }
    }
}
//滑动时隐藏上下边栏
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}
//判断结束拖拽之后的偏移量 改变segment的selectedIndex
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}
//上拉加载
- (void)loadnewdata
{
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html", (long)_number];
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        //
        NSLog(@"%@", result);
        NSArray *arr = result[@"videoSidList"];
        self.kindArr = [KindModel modelHanderWithArray:arr];
        [_collection reloadData];
        NSArray *arr1 = result[@"videoList"];
        NSArray *arrTemp = [Videomodel modelHanderWithArray:arr1];;
        for (NSInteger i = 0; i < 10; i++) {
            [_ListArr addObject:arrTemp[i]];
        }
        
        [_tableView reloadData];
        NSLog(@"%@", _ListArr);
    }];
    
    [_tableView.mj_footer endRefreshing];
    self.number += 10;
}


//数据处理
-(void)dataHandler
{
    //添加加载小菊花
    [MBProgressHUDManager showHUDtoView:self.view string:@"努力加载中"];
    NSString *str = @"http://c.m.163.com/nc/video/home/0-10.html";
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {

        //
        NSLog(@"%@", result);
        NSArray *arr = result[@"videoSidList"];
        self.kindArr = [KindModel modelHanderWithArray:arr];
        [_collection reloadData];
        NSArray *arr1 = result[@"videoList"];
        self.ListArr = [Videomodel modelHanderWithArray:arr1];
        [_tableView reloadData];
        NSLog(@"%@", _ListArr);
        [MBProgressHUDManager removeHUD];
    }];
    [_tableView.mj_header endRefreshing];
}
//创建collection个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _kindArr.count;
}
//点击进入分类详情
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    KindModel *m = _kindArr[indexPath.row];
    self.hidesBottomBarWhenPushed = YES;
    KindViewController *kindVC = [[KindViewController alloc]init];
    kindVC.sid = m.sid;
    [self.navigationController pushViewController:kindVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [kindVC release];
}
#pragma mark - 设置collection的cell中的内容
//collection中的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KindCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kindcell" forIndexPath:indexPath];
    if ([BlackManager sharedInstance].isNight) {
        [SetBlack setCellColorWithCell:cell];
    }else
    {
        [SetBlack setCellColorWithCell:cell];
    }
    KindModel *m = _kindArr[indexPath.row];
    [cell.picture sd_setImageWithURL:[NSURL URLWithString:m.imgsrc]placeholderImage:[UIImage imageNamed:@"pocket.png"]];
    cell.title.text = m.title;
    return cell;
}
//创建tableView的cell个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _ListArr.count;
}
//tableView的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 2;
}
#pragma mark - cell中的协议方法
//cell中的协议方法 分享只能在微博分享图片
-(void)shareWithindex:(NSIndexPath *)indexpath;
{
    NSLog(@"分享了");

    Videomodel *m = _ListArr[indexpath.row];
    
    [UMSocialData setAppKey:@"56a877ab67e58e508f000fb1"];
    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeVideo url:m.mp4_url];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:Nil shareText:m.title shareImage:nil shareToSnsNames:@[UMShareToSina, UMShareToTencent,UMShareToRenren] delegate:nil];
}
//cell的协议方法
-(void)pushLoginVC
{
    self.hidesBottomBarWhenPushed = YES;
    LoginViewController *login = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:login animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [login release];
}
#pragma mark - 夜间模式设置
//设置夜间模式  重写BaseViewController中的方法
-(void)setNightDayModel
{
    [SetBlack setBackgroundColorWithView:self.collection];
    [SetBlack setBackgroundColorWithView:self.tableView];
    //改变导航栏和tabbar的背景颜色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.tabBarController.tabBar.barStyle = UIBarStyleBlack;
    //    //导航栏背景颜色
    //    self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
    //    //导航栏上按钮的颜色
    //    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
-(void)setLightDayModel
{
    [SetBlack setBackgroundColorWithView:self.collection];
    [SetBlack setBackgroundColorWithView:self.tableView];
    //改变导航栏和tabbar的背景颜色
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.tabBarController.tabBar.barStyle = UIBarStyleDefault;
    
}
#pragma mark - tableView的cell点击事件
//tableView的cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击cell时移除正在播放视频
    if (self.movieView.view) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
    }
    __weak Videomodel *m = _ListArr[indexPath.row];
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/detail/%@.html", m.vid];
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        //
        NSString *path = result[@"vurl"];
        //push到下一页的时候隐藏tabbar
        self.hidesBottomBarWhenPushed = YES;
        VideoDetaileViewController *vc = [[VideoDetaileViewController alloc]init];
        vc.model = m;
        BOOL collect = [[NSUserDefaults standardUserDefaults]boolForKey:@"collect"];
        vc.i = collect;
        vc.pathstr = path;
        [self.navigationController pushViewController:vc animated:YES];
        //push回来的时候显示tabbar
        self.hidesBottomBarWhenPushed = NO;
        [vc release];
    }];
    
}
//tableView中的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    _cell.delegate = self;
    //判断是那种模式设置cell的背景颜色
    if ([BlackManager sharedInstance].isNight) {
         [SetBlack setCellColorWithCell:_cell];
        _cell.titleLable.textColor = [UIColor whiteColor];
    }else
    {
        [SetBlack setCellColorWithCell:_cell];
//         _cell.detailLable.textColor = [UIColor grayColor];
        _cell.titleLable.textColor = [UIColor blackColor];
    }
    Videomodel *m = _ListArr[indexPath.row];
    _cell.titleLable.text = m.title;
    _cell.indexpath = indexPath;
    _cell.model = m;
    _cell.detailLable.text = m.description1;
    //占位图
    [_cell.myImageView sd_setImageWithURL:[NSURL URLWithString:m.cover]placeholderImage:[UIImage imageNamed:@"pocket.png"]];
//    [_cell.myImageView sd_setImageWithURL:[NSURL URLWithString:m.cover]];
    _cell.myImageView.userInteractionEnabled = YES;
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_cell.myImageView addGestureRecognizer:tap];
    //点几下触发的方法
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [tap release];
    //将时间转换成00:00形式
    NSNumber *n = m.length;
    if (n.integerValue < 60) {
        _cell.timeLable.text = [NSString stringWithFormat:@"00: %ld", n.integerValue];
    }else{
    NSInteger fen = n.integerValue / 60;
    NSInteger miao = n.integerValue - 60 * fen;
    NSString *time = [NSString stringWithFormat:@"%ld : %ld", fen, miao];
    _cell.timeLable.text = time;
    }
    //将播放次数转换成0.0万形式
    NSNumber *play = m.playCount;
    NSInteger wan = play.integerValue / 10000;
    NSInteger qian = (play.integerValue - wan * 10000) / 1000;
    _cell.playLable.text = [NSString stringWithFormat:@"%ld.%ld万", wan, qian];
    _cell.str = m.mp4_url;
    _cell.commentLable.text = [m.replyCount.stringValue stringByAppendingString:@"评论"];
   
    //数据库里收藏的内容
    DateBaseManager *dbManager = [DateBaseManager shareInstance];
    [dbManager openDB];
    
    NSMutableArray *arr = [dbManager select];
    self.i = 0;
    for(Videomodel *model in arr)
    {
        NSLog(@"%@", model.title);
        if ([model.title isEqualToString:m.title])
        {
            _i = 1;
        }
    }
    if (_i == 1){
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"collect"];
    }
    if (_i == 0){
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"collect"];
    }
    return _cell;
}

//点击图片触发的方法
-(void)tapAction:(UITapGestureRecognizer *)sender
{
    //点开新的关闭旧的
    if (self.movieView.view) {
        [self.movieView.view removeFromSuperview];
    }
    //点击的哪个ImageView
    UIView *view = sender.view;
    //imageView->contentView->cell
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    self.indexpath = [self.tableView indexPathForCell:cell];//获取被点击的cell的indexPath
    Videomodel *model = _ListArr[_indexpath.row];
    self.movieView = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    self.movieView.view.frame = CGRectMake(10, 60, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.height / 3 + 8);
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [cell addSubview:self.movieView.view];
//    [_movieView release];
    //添加视频关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"iconfont-cha"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    //设置按钮的相对坐标
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.movieView.view).with.offset(-5);
        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
}
- (void)close:(UIButton *)button {
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
